var app = getApp();
var webhost = app.globalData.webhost;
var upLoadHost = app.globalData.upLoadHost;
var util = require('../../utils/date.js')

Page({
  data: {
    index: 0,
    ruleIndex: 0,
    applyDate: '',
    amount: '',
    price:'',
    money: '',
    remarks: '',
    imgs: [],
    upImgs:[],
    claimTypeList: [],
    claimTypeCodeList: [],
    billingRules: [],
    billingRulesCode: [],
    sessionid: '',
    driverName: '',
    feeAppData: {},
    planData: {},
    taskData:{},
    data: {},
    task: false,
  },

  bindDate: function(e) {
    var that = this;
    var date = e.detail.value;
    that.setData({
      applyDate: date
    })
  },

  bindStatus: function(e) {
    var that = this;
    var index = e.detail.value;
    that.setData({
      index: parseInt(index)
    })
  },

  bindRulesStatus: function (e) {
    var that = this;
    var ruleIndex = e.detail.value;
    that.setData({
      ruleIndex: parseInt(ruleIndex)
    })
  },

  inputAmount: function(e) {
    var that = this;
    var price = that.data.price;
    that.setData({
      amount: e.detail.value,
    })
    if(price){
      that.setData({
        money: parseFloat(e.detail.value * price).toFixed(2)
      })
    }
  },

  inputPrice: function(e) {
    var that = this;
    var amount = that.data.amount;
    that.setData({
      price: e.detail.value,
    })
    if(amount){
      that.setData({
        money: parseFloat(e.detail.value * amount).toFixed(2)
      })
    }
  },

  inputMoney(e){
    this.setData({
      money: e.detail.value
    })
  },

  inputRemarks: function(e) {
    var that = this;
    that.setData({
      remarks: e.detail.value,
    })
  },

  // 上传图片
  chooseImg: function(e) {
    var that = this;
    var imgs = this.data.imgs;
    if (imgs.length >= 9) {
      this.setData({
        lenMore: 1
      });
      setTimeout(function() {
        that.setData({
          lenMore: 0
        });
      }, 2500);
      return false;
    }
    wx.chooseImage({
      // count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var imgs = that.data.imgs;
        for (var i = 0; i < tempFilePaths.length; i++) {
          if (imgs.length >= 9) {
            that.setData({
              imgs: imgs
            });
            return false;
          } else {
            imgs.push(tempFilePaths[i]);
          }
        }
        that.setData({
          imgs: imgs
        });
      }
    });
  },

  addPhoto: function(e) {
    var that = this;
    var upPicData = that.data.upPicData
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var imgs = that.data.imgs;
        var upImgs = that.data.upImgs;
        var url = upLoadHost;
        if (tempFilePaths) {
          for (var i = 0; i < tempFilePaths.length; i++) {
            var now = new Date();
            var filename = upPicData.dir + '/' + app.globalData.driverAccount + util.Format("yyyyMMddhhmmssS", now);
            upImgs.push(url + '/' + filename);
            imgs.push(tempFilePaths[i]);
            wx.uploadFile({
              url: url,
              filePath: tempFilePaths[i],
              name: 'file',
              formData: {
                name: tempFilePaths[i],
                key: filename,
                policy: that.data.upPicData.policy,
                OSSAccessKeyId: that.data.upPicData.accessid,
                success_action_status: "200",
                signature: that.data.upPicData.signature
              },
              success: function(res) {
                var data = res.data;
                if (imgs.length <= 10) {
                  that.setData({
                    imgs: imgs,
                    upImgs: upImgs,
                  })
                } else {
                  wx.showModal({
                    title: '提示',
                    showCancel: false,
                    confirmColor: '#118EDE',
                    content: '图片数量不能超过10张',
                    success: function(res) {
                      if (res.confirm) {
                        imgs = imgs.slice(0, 10);
                        that.setData({
                          imgs: imgs,
                          upImgs: upImgs,
                        })
                      }
                    }
                  })
                }
              }
            })
          }
        }
      }
    })
  },

  upLoadImg(tempFilePaths, i) {
    var that = this;
    var upPicData = that.data.upPicData;
    wx.showLoading({
      title: '图片上传中',
    })
    var fileName = upPicData.dir + '/' + app.globalData.driverAccount + util.Format("yyyyMMddhhmmssS", new Date());
    var url = upLoadHost;
    var imgs = that.data.imgs;
    var item = {
      picturePath: url + '/' + fileName
    }
    const uploadTask = wx.uploadFile({
      url: url,
      filePath: tempFilePaths[i],
      name: 'file',
      formData: {
        name: tempFilePaths[i],
        key: fileName,
        policy: upPicData.policy,
        OSSAccessKeyId: upPicData.accessid,
        success_action_status: "200",
        signature: upPicData.signature
      },
      success(res) {
        imgs.push(item);
        that.setData({
          imgs: imgs
        })
        i++;
        if (i < tempFilePaths.length) {
          that.upLoadImg(tempFilePaths, i);
        }else{
          wx.hideLoading();
        }
      },
      fail() {
        wx.showToast({
          title: '第' + i + '张图片上传失败',
          icon: 'none'
        })
      }
    })
    uploadTask.onProgressUpdate((res) => {
      console.log('上传进度', res.progress)
      console.log('已经上传的数据长度', res.totalBytesSent)
      console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })
  },

  picClick() {
    var that = this;
    if (!that.data.upPicData.accessid) {
      wx.showToast({
        title: '未获取上传权限',
        icon: 'none'
      })
      return false;
    }
    var count = 9;
    count = 9 - that.data.imgs.length;
    if (count <= 0) {
      wx.showToast({
        title: '最多上传9张图片',
        icon: 'none'
      })
      return false;
    }
    wx.chooseImage({
      count: count,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        var tempFilePaths = res.tempFilePaths;
        if (tempFilePaths) {
          var i = 0;
          that.upLoadImg(tempFilePaths, i);
        }
      }
    })
  },


  // 删除图片
  deleteImg: function(e) {
    var imgs = this.data.imgs;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    this.setData({
      imgs: imgs
    });
  },
  // 预览图片
  previewImg: function (e) {
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    //所有图片
    var imgs = this.data.imgs;
    var preImgs = [];
    for (var i = 0; i < imgs.length; i++) {
      preImgs[i] = imgs[i].picturePath;
    }
    wx.previewImage({
      //当前显示图片
      current: preImgs[index],
      //所有图片
      urls: preImgs
    })
  },

  
  //提交费用申请到审核阶段
  submit: function() {
    var that = this;
    var planData = that.data.planData;
    var taskData = that.data.taskData;
    if (!that.data.money) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        confirmColor: '#118EDE',
        content: '请输入申请金额',
        success: function(res) {
          if (res.confirm) {}
        }
      })
      return false;
    }
    var data = {
      'type': 'submit',
      id: that.data.id,
      reimburseNo: '',
      reimburseDate: that.data.applyDate,
      reimburseAssociateNo: '',
      reimburseProject: that.data.claimTypeCodeList[that.data.index],
      reimburseAmount: that.data.money,
      reimburseRemarks: that.data.remarks,
      reimburseStatus: '',
      n1: parseFloat(parseFloat(that.data.price).toFixed(2)),
      n2: that.data.amount,
      n3: that.data.billingRulesCode[that.data.ruleIndex],
    }
    // var imgs = that.data.imgs;
    // var dataList = new Array();
    // for (var i = 0; i < imgs.length; i++) {
    //   dataList.push({
    //     picturePath: imgs[i]
    //   })
    // }
    if (that.data.task) {
      var parameters = [{
        String: {
          driverAccount: app.globalData.driverAccount,
          sessionid: app.globalData.sessionid,
          planId: planData.planId,
          taskid: taskData.taskid,
          taskCode: taskData.taskCode,
          actionCode: 'COST',
          data: data,
          dataList: that.data.imgs
        }
      }]
    } else {
      var parameters = [{
        String: {
          driverAccount: app.globalData.driverAccount,
          sessionid: app.globalData.sessionid,
          planId: planData.planId,
          taskCode: planData.taskCode,
          actionCode: 'COST',
          data: data,
          dataList: that.data.imgs
        }
      }]
    }
    wx.request({
      url: webhost,
      data: {
        eap_username: "driver",
        eap_password: "Driver2018",
        boId: "tspdriver_tsp2DriverServiceBO_bo", //调用的bo
        methodName: 'feeApplication', //调用的具体方法
        returnType: "json", //返回参数类型
        parameters: JSON.stringify(parameters)
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function(res) {
        var code = res.data.code;
        if (code == '000000') {
          var data = res.data.data;
          wx.showModal({
            title: '提示',
            showCancel: false,
            confirmColor: '#118EDE',
            content: '提交成功!',
            success: function(res) {
              if (res.confirm) {
                var pages = getCurrentPages();
                pages[pages.length - 2].onPullDownRefresh();
                wx.navigateBack({});
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            showCancel: false,
            confirmColor: '#118EDE',
            content: res.data.msg,
            success: function(res) {
              if (code == '003000') {
                if (res.confirm) {
                  wx.reLaunch({
                    url: '../login/login'
                  })
                }
              }
            }
          })
        }
      }
    })
  },
  //新创建一个费用申请，未到审核阶段
  save: function () {
    var that = this;
    var planData = that.data.planData;
    var taskData = that.data.taskData;
    if (!that.data.money) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        confirmColor: '#118EDE',
        content: '请输入申请金额',
        success: function (res) {
          if (res.confirm) { }
        }
      })
      return false;
    }
    var data = {
      'type': 'new',
      id: that.data.id,
      reimburseNo: '',
      reimburseDate: that.data.applyDate,
      reimburseAssociateNo: '',
      reimburseProject: that.data.claimTypeCodeList[that.data.index],
      reimburseAmount: that.data.money,
      reimburseRemarks: that.data.remarks,
      reimburseStatus: '',
      n1: parseFloat(parseFloat(that.data.price).toFixed(2)),
      n2: that.data.amount,
      n3: that.data.billingRulesCode[that.data.ruleIndex],
    }
    var imgs = that.data.imgs;
    var dataList = new Array();
    for (var i = 0; i < imgs.length; i++) {
      dataList.push({
        picturePath: imgs[i]
      })
    }
    if (that.data.task) {
      var parameters = [{
        String: {
          driverAccount: app.globalData.driverAccount,
          sessionid: app.globalData.sessionid,
          planId: planData.planId,
          taskid: taskData.taskid,
          taskCode: taskData.taskCode,
          actionCode: 'COST',
          data: data,
          dataList: dataList
        }
      }]
    } else {
      var parameters = [{
        String: {
          driverAccount: app.globalData.driverAccount,
          sessionid: app.globalData.sessionid,
          planId: planData.planId,
          taskCode: planData.taskCode,
          actionCode: 'COST',
          data: data,
          dataList: dataList
        }
      }]
    }
    wx.request({
      url: webhost,
      data: {
        eap_username: "driver",
        eap_password: "Driver2018",
        boId: "tspdriver_tsp2DriverServiceBO_bo", //调用的bo
        methodName: 'feeApplication', //调用的具体方法
        returnType: "json", //返回参数类型
        parameters: JSON.stringify(parameters)
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {
        var code = res.data.code;
        if (code == '000000') {
          var data = res.data.data;
          wx.showModal({
            title: '提示',
            showCancel: false,
            confirmColor: '#118EDE',
            content: '提交成功!',
            success: function (res) {
              if (res.confirm) {
                var pages = getCurrentPages();
                pages[pages.length - 2].onPullDownRefresh();
                wx.navigateBack({});
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            showCancel: false,
            confirmColor: '#118EDE',
            content: res.data.msg,
            success: function (res) {
              if (code == '003000') {
                if (res.confirm) {
                  wx.reLaunch({
                    url: '../login/login'
                  })
                }
              }
            }
          })
        }
      }
    })
  },
  reset:function(){
    var that = this;
    var curDate = util.getFormatDate(); 
    that.setData({
      applyDate: curDate,
      index:0,
      amount: '',
      price: '',
      money: '',
      remarks: '',
      imgs: [],
    })
  },

  //获取数据
  queryFeeApplicationDetail: function() {
    var that = this;
    var id = that.data.id;
    var sessionid = app.globalData.sessionid;
    var driverAccount = app.globalData.driverAccount;
    var data = [{
      String: {
        driverAccount: driverAccount,
        sessionid: sessionid,
        id: id
      }
    }]
    wx.request({
      url: webhost,
      data: {
        eap_username: "driver",
        eap_password: "Driver2018",
        boId: "tspdriver_tsp2DriverServiceBO_bo", //调用的bo
        methodName: 'queryFeeApplicationDetail', //调用的具体方法
        returnType: "json", //返回参数类型
        parameters: JSON.stringify(data)
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function(res) {
        var code = res.data.code;
        if (code == '000000') {
          if (res.data.data.reimburseStatus == "B030") {
            that.setData({
              isReject: true
            })
          }
          that.setData({
            feeAppData: res.data.data
          })
        } else {
          wx.showModal({
            title: '提示',
            showCancel: false,
            confirmColor: '#118EDE',
            content: res.data.msg,
            success: function(res) {
              if (code == '003000') {
                if (res.confirm) {
                  wx.reLaunch({
                    url: '../login/login'
                  })
                }
              }
            }
          })
        }
      }
    })
  },

  onLoad: function(options) {
    var that = this;
    var curDate = util.getFormatDate();
    var taskData = app.globalData.task;
    if (taskData && taskData.taskCode == 'TIHU') {
      taskData.customerName = '';
      taskData.orderTaskNO = '';
    };

    that.setData({
      applyDate: curDate,
      planData: app.globalData.plan ,
      taskData: taskData ,
      task: options.task ? true : false
    });
    var permissionParam = [{
      String: {
        sessionid: app.globalData.sessionid
      }
    }]

    //获取计费单位
    wx.request({
      url: webhost,
      data: {
        eap_username: "driver",
        eap_password: "Driver2018",
        boId: "tspdriver_tsp2DriverServiceBO_bo", //调用的bo
        methodName: 'getCodeList', //调用的具体方法
        returnType: "json", //返回参数类型
        parameters: "[{ String: { 'codeListKey': 'tsp2_chargeUnit' } }]"
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function(res) {
        var code = res.data.code;
        var billingRules = [];
        var billingRulesCode = [];
        if (code == '000000') {
          for (var i = 0; i < res.data.codeList.length; i++) {
            billingRules[i] = res.data.codeList[i].codeName
            billingRulesCode[i] = res.data.codeList[i].codeValue
          }
          that.setData({
            billingRules: billingRules,
            billingRulesCode: billingRulesCode
          })
        } else {
          wx.showModal({
            title: '提示',
            showCancel: false,
            confirmColor: '#118EDE',
            content: res.data.msg,
            success: function(res) {
              if (res.confirm) {}
            }
          })
        }
      },
      fail: function(res) {
        wx.showModal({
          title: '提示',
          showCancel: false,
          confirmColor: '#118EDE',
          content: '服务器异常',
          success: function(res) {
            if (res.confirm) {}
          }
        })
      }
    })

    //拉取费用类型
    wx.request({
      url: webhost,
      data: {
        eap_username: "driver",
        eap_password: "Driver2018",
        boId: "tspdriver_tsp2DriverServiceBO_bo", //调用的bo
        methodName: 'getCodeList', //调用的具体方法
        returnType: "json", //返回参数类型
        parameters: "[{ String: { 'codeListKey': 'tsp2_nameOfWayFee' } }]"
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {
        var code = res.data.code;
        var claimTypeList = [];
        var claimTypeCodeList = [];
        if (code == '000000') {
          for (var i = 0; i < res.data.codeList.length; i++) {
            claimTypeList[i] = res.data.codeList[i].codeName
            claimTypeCodeList[i] = res.data.codeList[i].codeValue
          }
          that.setData({
            claimTypeList: claimTypeList,
            claimTypeCodeList: claimTypeCodeList
          })
        } else {
          wx.showModal({
            title: '提示',
            showCancel: false,
            confirmColor: '#118EDE',
            content: res.data.msg,
            success: function (res) {
              if (res.confirm) { }
            }
          })
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          showCancel: false,
          confirmColor: '#118EDE',
          content: '服务器异常',
          success: function (res) {
            if (res.confirm) { }
          }
        })
      }
    })
    //获取上传权限
    wx.request({
      url: webhost,
      data: {
        eap_username: "driver",
        eap_password: "Driver2018",
        boId: "tspdriver_tsp2DriverServiceBO_bo", //调用的bo
        methodName: 'getFileUploadPermission', //调用的具体方法
        returnType: "json", //返回参数类型
        parameters: JSON.stringify(permissionParam)
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function(res) {
        var code = res.data.code;
        if (code == '000000') {
          var data = res.data.data;
          that.setData({
            upPicData: data,
            accessid: data.accessid,
            policy: data.policy,
            signature: data.signature,
            dir: data.dir
          })
        } else {
          wx.showModal({
            title: '提示',
            showCancel: false,
            confirmColor: '#118EDE',
            content: res.data.msg,
            success: function(res) {
              if (code == '003000') {
                if (res.confirm) {
                  wx.reLaunch({
                    url: '../login/login'
                  })
                }
              }
            }
          })
        }
      }
    })
  },

  onShow: function() {

  },

  onHide: function() {

  },

  onPullDownRefresh: function() {

  },

  onReachBottom: function() {

  },

  onShareAppMessage: function() {

  }
})